package nl.runnable.solr.xslt;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;

/**
 * {@link PushbackInputStream} with simple support for mark and reset. Used internally by {@link PushbackContentStream}.
 * 
 * @author Laurens Fridael
 * 
 */
class MarkSupportingPushbackInputStream extends PushbackInputStream {

	private ByteArrayOutputStream buffer;

	MarkSupportingPushbackInputStream(final InputStream in, final int size) {
		super(in, size);
		buffer = new ByteArrayOutputStream(size);
	}

	MarkSupportingPushbackInputStream(final InputStream in) {
		this(in, 1024);
	}

	@Override
	public boolean markSupported() {
		return true;
	}

	@Override
	public synchronized void mark(final int readlimit) {
		buffer = new ByteArrayOutputStream(readlimit);
	}

	@Override
	public synchronized void reset() throws IOException {
		unread(buffer.toByteArray());
		buffer.reset();
	}

	@Override
	public int read() throws IOException {
		final int b = super.read();
		if (b > -1) {
			buffer.write(b);
		}
		return b;
	}

	@Override
	public int read(final byte[] b) throws IOException {
		final int bytesRead = super.read(b);
		if (bytesRead > -1) {
			buffer.write(b, 0, bytesRead);
		}
		return bytesRead;
	}

	@Override
	public int read(final byte[] b, final int off, final int len) throws IOException {
		final int bytesRead = super.read(b, off, len);
		if (bytesRead > -1) {
			buffer.write(b, off, bytesRead);
		}
		return bytesRead;
	}

}
